﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace System.Windows
{

    internal static class FrameworkElementExtensions
    {

        public static object FindNameRecursive(this FrameworkElement element, string name)
        {
            FrameworkElement rootVisual = element.GetRootVisual();
            if (rootVisual == null)
            {
                return null;
            }

            return rootVisual.FindName(name);
#if FALSE
            while (element != null) {
                object value = element.FindName(name);
                if (value != null) {
                    return value;
                }

                element = element.GetParent();
            }

            return null;
#endif
        }

        public static object FindRecursive(this FrameworkElement element, Type type)
        {
            while (element != null)
            {
                element = element.GetParentVisual();

                if ((element != null) && type.IsAssignableFrom(element.GetType()))
                {
                    return element;
                }
            }

            return null;
        }

        public static object FindResource(this FrameworkElement element, string key)
        {
            while (element != null)
            {
                object value = element.Resources[key];
                if (value != null)
                {
                    return value;
                }

                element = element.GetParentVisual();
            }

            return null;
        }

        public static FrameworkElement GetParentVisual(this FrameworkElement element)
        {
            return VisualTreeHelper.GetParent(element) as FrameworkElement;
        }

        public static FrameworkElement GetRootVisual(this FrameworkElement element)
        {
            FrameworkElement parent = null;
            while (element != null)
            {
                parent = element;
                if (parent is UserControl)
                {
                    // HACK: A UserControl parented to another UserControl has a non-null
                    //       parent; however we want to consider the UserControl as the
                    //       root visual for its contents...
                    break;
                }

                element = element.Parent as FrameworkElement;
            }

            return parent;
        }
    }
}
